package com.p2p.core;

import android.content.Context;

import com.p2p.define.P2PRoomType;
import com.p2p.listener.P2PGlobalListener;
import com.p2p.listener.P2PSocketListener;
import com.p2p.listener.P2PRoomListener;
import com.p2p.model.P2PRoom;

import org.webrtc.PeerConnectionFactory;
import org.webrtc.VideoRendererGui;

import java.util.HashMap;
import java.util.Map;

public class P2PFacade {
    private final static String TAG = P2PFacade.class.getCanonicalName();

    private static Context mContext;
    private static P2PGlobalListener roomListener;
    private static P2PWebSocketClient socketClient;
    private static Map<String, P2PRoom> roomMap = new HashMap<>();

    public static void initGlobal(Context context) {
        mContext = context;
        PeerConnectionFactory.initializeAndroidGlobals(context, true, true, true, VideoRendererGui.getEGLContext());
    }

    public static void onCreate(P2PGlobalListener listener, String uid, String name) {
        //mContext = context;
        roomListener = listener;
        socketClient = P2PWebSocketClient.getInstance(new P2PSocketListener() {
            @Override
            public void initSuccess() {
                roomListener.onInitSuccess();
            }

            @Override
            public void joinSuccess() {

            }
        });
        socketClient.init(uid, name);
    }

    public static void joinRoom(String roomId, P2PRoomType roomType, P2PRoomListener roomListener) {
        P2PPeerClient client = new P2PPeerClient(roomId, mContext, roomListener);
        socketClient.join(roomId, roomType);
        roomMap.put(client.getId(), client);
    }

    public static void onPause() {
        for (Map.Entry<String, P2PRoom> entry : roomMap.entrySet()) {
            entry.getValue().onPause();
        }
    }

    public static void onResume() {
        for (Map.Entry<String, P2PRoom> entry : roomMap.entrySet()) {
            entry.getValue().onResume();
        }
    }

    public static void onDestroy() {
        for (Map.Entry<String, P2PRoom> entry : roomMap.entrySet()) {
            entry.getValue().onDestroy();
        }
    }

}
